package com.zxj.shop.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxj.shop.admin.entity.Role;
import com.zxj.shop.admin.entity.User;
import com.zxj.shop.admin.service.RoleService;
import com.zxj.shop.admin.service.ShiroService;
import com.zxj.shop.admin.shiro.vo.PageBean;
import com.zxj.shop.admin.shiro.vo.PageVO;
import com.zxj.shop.admin.shiro.vo.ResultVO;
import com.zxj.shop.admin.utils.CosUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Api(tags = "用户管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/admin/users/user")
public class UserApiController {

    @Autowired
    ShiroService shiroService;
    @Autowired
    RoleService  roleService;

    private final CosUtil cosUtil;

    @GetMapping("/list")
    public PageVO<User> list(User user, PageBean pageBean) {
        IPage<User> userPage = shiroService.page(new Page<>(pageBean.getPage(), pageBean.getLimit()), user);
        return PageVO.pageVO(userPage.getRecords(), userPage.getTotal());
    }


    @PostMapping("/confirm/add")
    public ResultVO confirmAdd(User sysAccount) {
        shiroService.createUser(sysAccount);
        return ResultVO.success("添加成功");
    }


    @PostMapping("/confirm/edit")
    @ApiOperation(value = "用户编辑")
    public ResultVO confirmEdit(User sysAccount) {
        shiroService.updateUser(sysAccount);
        return ResultVO.success();
    }

    @PostMapping("/view")
    public ResultVO<Map<String,Object>> view(Integer userId) {
        Map<String,Object> maps = new HashMap<>();
        Map<Integer,String> userRoles = roleService.getUserRoles(userId.toString()).
                    stream().collect(Collectors.toMap(Role::getId,Role::getName));
        List<Role> roles = roleService.getRoles();
        for (Role r: roles) {
            String role =  userRoles.get(r.getId());
            if(StringUtils.isNotBlank(role)) {
                r.setChecked(true);
            }
        }
        User user = shiroService.findByUserId(userId);
        if(StringUtils.isNotBlank(user.getIcon())) {
            user.setSingUrl(cosUtil.getObject(user.getIcon()));
        }
        maps.put("role", roles);
        maps.put("user", user);
        return ResultVO.success(maps);
    }

}
